﻿using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace AME.WebAppCore
{
    public static class AutoInjection
    {
        /// <summary>
        /// 扫描程序集将标记AutoDI的服务注册
        /// </summary>
        /// <param name="externalAssembly"></param>
        /// <param name="services"></param>
        public static void AutoDependencyInjection(Assembly externalAssembly, IServiceCollection services)
        {
            var typesWithAutoDI = externalAssembly.GetTypes()
                .Where(t => t.GetCustomAttributes(typeof(AutoDI), true).Any());

            foreach (var type in typesWithAutoDI)
            {
                var autoDIAttribute = type.GetCustomAttributes(typeof(AutoDI), true).FirstOrDefault() as AutoDI;

                if (autoDIAttribute != null)
                {
                    // 根据 AutoDI 属性的配置决定如何注册
                    var lifetime = autoDIAttribute.LifeTime;  // 例如 AddTransient、AddScoped、AddSingleton

                    // 找出接口和实现类
                    var interfaces = type.GetInterfaces();
                    if (interfaces.Length > 0)
                    {
                        foreach (var iface in interfaces)
                        {
                            switch (lifetime)
                            {
                                case ServiceLifetime.Transient:
                                    services.AddTransient(iface, type);
                                    break;
                                case ServiceLifetime.Scoped:
                                    services.AddScoped(iface, type);
                                    break;
                                case ServiceLifetime.Singleton:
                                    services.AddSingleton(iface, type);
                                    break;
                                default:
                                    services.AddTransient(iface, type); // 默认注册为 Transient
                                    break;
                            }
                        }
                    }
                    else
                    {
                        // 如果没有接口，只注册实现类本身
                        switch (lifetime)
                        {
                            case ServiceLifetime.Transient:
                                services.AddTransient(type);
                                break;
                            case ServiceLifetime.Scoped:
                                services.AddScoped(type);
                                break;
                            case ServiceLifetime.Singleton:
                                services.AddSingleton(type);
                                break;
                            default:
                                services.AddTransient(type); // 默认注册为 Transient
                                break;
                        }
                    }
                }
            }
        }
    }
}
